﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Domain.UserManageDomain;
using Zocono.WCS.Infrastructure.ApllicationDto;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoWcsManage;

namespace Zocono.WCS.Domain.UserManageDomain
{
    public class TracesService : ITracesService
    {
        private readonly ITracesRepository _tracesRepository;

        public TracesService(ITracesRepository tracesRepository)
        {
            _tracesRepository = tracesRepository;
        }
        /// <summary>
        /// 保存操作日志
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<bool> AddTraces(TracesInfo info)
        {
            return await _tracesRepository.InsertAsync(info);
        }

        public async Task<PageDto<TracesInfoDto>> GetTraces(TracesInfoDto info)
        {
            PageModel page = new PageModel { PageIndex = info.PageIndex, PageSize = info.PageSize, };
            PageDto<TracesInfoDto> pageDto = new PageDto<TracesInfoDto>();
            RefAsync<int> totalNumber = 0;
            var exp = Expressionable.Create<TracesInfo>();
            exp.AndIF(info.OperationType != 0, l => l.OperationType == info.OperationType);
            exp.AndIF(!string.IsNullOrEmpty(info.UserName), l => l.UserName.Contains(info.UserName)   );
            exp.AndIF(!string.IsNullOrEmpty(info.StarTime), l => l.LogTime >= info.StarTime.ToDateTimeFormat("yyyy-MM-dd HH:mm"));
            exp.AndIF(!string.IsNullOrEmpty(info.EndTime), l => l.LogTime < info.EndTime.ToDateTimeFormat("yyyy-MM-dd HH:mm"));
            var result = await _tracesRepository.AsSugarClient().Queryable<TracesInfo>().Where(exp.ToExpression()).OrderBy(l => l.LogTime, OrderByType.Desc).Select(l => new TracesInfoDto
            {
                ID= l.ID,
                UserID= l.UserID,
                UserName= l.UserName,
                LogTime= l.LogTime,
                Ip= l.Ip,
                FunctionID= l.FunctionID,
                FullName= l.FullName,
                RequestUrl= l.RequestUrl,
                Parameter= l.Parameter,
                OperationType= l.OperationType
            }).ToPageListAsync(page.PageIndex, page.PageSize, totalNumber);
            pageDto.Result = result;
            pageDto.Total = totalNumber;
            return pageDto;
        }
    }
}
